package com.yh.correct.interceptor;


import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.IPUtils;
import com.yh.correct.model.ActiveUser;
import com.yh.correct.model.SysLog;
import com.yh.correct.service.ISysLogService;

/**
 * 日志拦截器
 * @author Administrator
 *
 */
public class LogInterceptor implements HandlerInterceptor{
	
	@Autowired
	private ISysLogService logService;
	private static final Logger logger=LogManager.getLogger(LogInterceptor.class);
	private ThreadLocal<Long> startTime=new ThreadLocal<Long>();
	private ThreadLocal<Long> endTime=new ThreadLocal<Long>();
	private ThreadLocal<Long> runtime=new ThreadLocal<Long>();
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		startTime.set(System.currentTimeMillis());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
		endTime.set(System.currentTimeMillis());
		runtime.set(endTime.get()-startTime.get());
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerMethod handlerMethod=null;
		String ip=null;
		String mac=null;
		ActiveUser activeUser=null;
		try {
			handlerMethod = (HandlerMethod) handler;   
			ip = IPUtils.getIpAddr(request);
			mac = IPUtils.getMAC(ip);
			activeUser = (ActiveUser) request.getSession().getAttribute("activeUser");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			
		}
		if(activeUser!=null){
			SysLog log=new SysLog();
			log.setUsername(activeUser.getRealname());
			log.setIp(ip);
			log.setMac(mac);
			log.setUrl(request.getRequestURI());
			log.setType(request.getMethod());
			log.setClassname(handlerMethod.getBeanType().getName());
			log.setMethod(handlerMethod.getMethod().getName());
			log.setTime(runtime.get().intValue());
			log.setCreatetime(new Timestamp(System.currentTimeMillis()));
			try {
				logService.insertSysLog(log);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.debug("写入数据库日志失败！"+e.getMessage());
			}
		}
		
	 
	}

}
